22. Exercise: Implement a Click Listener

L7 36 Implement A Click Listener SC

Now it’s your turn to complete this exercise yourself!

In this exercise you'll implement a ClickListener and bind it in the adapter.

  1. In SleepNightAdapter, create a new class called SleepNightListener.

    The listener class receives a SleepNight object and passes its nightId field:

    class SleepNightListener(val clickListener: (sleepId: Long) -> Unit) {
        fun onClick(night: SleepNight) = clickListener(night.nightId)
    }


  2. Wire up the new listener to class to your list_item_sleep_night.xml by creating new variable.

    <variable
        name="clickListener" type="com.example.android.trackmysleepquality.sleeptracker.SleepNightListener"/>


  3. In order to tell the view to call your click listener, add your click listener to onClick property of the ConstaintLayout.

 android:onClick="@{() -> clickListener.onClick(sleep)}"


  1. Add a SleepNightListener reference to the SleepNightAdapter class declaration.
class SleepNightAdapter(val clickListener: SleepNightListener) 


  1. To finish the adapter, add clickListener to DataBinding in onBindViewHolder method.

    Edit the call to holder.bind to pass the click listener:

holder.bind(clickListener,getItem(position)!!) 


  1. Following the prior step, pass the click listener to bind() and add it to the binding:

    fun bind(clickListener: SleepNightListener, item: SleepNight) {
          binding.sleep = item
          binding.clickListener = clickListener
          binding.executePendingBindings()
    }


  2. In SleepTrackerFragment, fix the error on the adapter = SleepNightAdapter() declaration by passing the SleepNightListener object.

    Have the listener display the nightId in a toast message when the user clicks the item in the grid.

    val adapter = SleepNightAdapter(SleepNightListener { nightId ->
         Toast.makeText(context, "${nightId}", Toast.LENGTH_LONG).show()
    })


  3. Build and run the code, and try out your new click listener!

If you want to start at this step, you can download this exercise from: Step.11-Exercise-Implement-a-Click-Listener.

You will find plenty of //TODO comments to help you complete this exercise, and if you get stuck, go back and watch the video again.

Once you’re done, you can check your solution against the solution we’ve provided here: Step.11-Solution-Implement-a-Click-Listener, or using this git diff.

Task Description:

Complete the steps below to implement a ClickListener and bind it in the adapter.

Task List:

Task Feedback:

A toast to you!